package com.thtfpc.utility;

import java.net.*;
import java.util.Enumeration;

public class InetUtil {
    public static InetAddress getLocalHostAddress() throws UnknownHostException {
        InetAddress jdkSuppliedAddress2 = InetAddress.getLocalHost();
        Enumeration allNetInterfaces;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (netInterface.isLoopback()
                        || netInterface.isUp() == false
                        || netInterface.isVirtual()
                        || netInterface.getName().indexOf("docker") != -1
                        || netInterface.getName().indexOf("lo") != -1) {
                    continue;
                }
                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip;
                        }
                    }
                }
            }
        }
        catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        if (jdkSuppliedAddress == null) {
            throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
        }
        return jdkSuppliedAddress;
    }

    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException ex) {
            ex.printStackTrace();
            try {
                return InetAddress.getLocalHost().getHostAddress();
            }
            catch (UnknownHostException ex2) {
                ex2.printStackTrace();
            }
        }

        return "undefined host";
    }
}
